package com.sxpi.zixun.config.interceptor;

import com.sxpi.zixun.common.anno.IgnoreToken;
import com.sxpi.zixun.common.enums.AdminUserResultEnum;
import com.sxpi.zixun.common.ex.PugValidatorException;
import com.sxpi.zixun.common.utils.fn.asserts.Vsserts;
import com.sxpi.zixun.service.jwt.JwtService;
import com.sxpi.zixun.config.redis.AdminRedisKeyManager;
import com.sxpi.zixun.local.UserThreadLocal;
import com.sxpi.zixun.pojo.AdminUser;
import com.sxpi.zixun.service.adminuser.IAdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author 蓝欣
 */
@Component
@Slf4j
public class PassportLoginInterceptor implements HandlerInterceptor, AdminRedisKeyManager {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private IAdminUserService iAdminUserService;

    /**
     * 管理员可以做到实时性的一个操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 把handler从Object对象转换为具体的对象HandlerMethod
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        Class<?> beanType = handlerMethod.getBeanType();
        IgnoreToken annotationMethod = method.getAnnotation(IgnoreToken.class);
        IgnoreToken annotationClass = beanType.getAnnotation(IgnoreToken.class);
        // 方法级别和方法级别的判断
        if(annotationMethod != null || annotationClass != null){
            return true;
        }
        String token = jwtService.getToken(request);
        // 如果token没有传递，直接抛出
        Vsserts.isEmptyEx(token,AdminUserResultEnum.TOKEN_NOT_FOUND);
        String tokenUserId = jwtService.getTokenUserId(request);
        // 检验token是否合法
        boolean verify = jwtService.refreshTokenRedis(token,tokenUserId,response);
        Vsserts.isNotTrueEx(verify,AdminUserResultEnum.TOKEN_ERROR);
        Vsserts.isNullEx(tokenUserId,AdminUserResultEnum.TOKEN_NOT_FOUND);
        // 根据用户Id查询用户信息
        AdminUser adminUser = iAdminUserService.getById(Long.parseLong(tokenUserId));
        Vsserts.isNullEx(adminUser,AdminUserResultEnum.TOKEN_NOT_FOUND);
        // 拉黑处理
        if(adminUser.getStatus() != null && adminUser.getStatus().equals(0)){
            throw new PugValidatorException(AdminUserResultEnum.USER_FORBIDDEN_ERROR);
        }
        // 用户的删除
        if(adminUser.getIsdelete() != null && adminUser.getIsdelete().equals(1)){
            throw new PugValidatorException(AdminUserResultEnum.USER_FORBIDDEN_ERROR);
        }
        // 把用户信息放到线程池
        UserThreadLocal.put(adminUser);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
